package com.wiselink.fastbox.orderplacement;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.wiselink.fastbox.FastBoxBaseAPI;

import java.util.*;

/**
 * 配送说明
 */
public class DeliveryInstruction extends FastBoxBaseAPI {
    private final Map<String, String> objectMap;

    private final List<ResultVO> vos = new ArrayList<>();

    public DeliveryInstruction(Map<String, String> objectMap) {
        this.objectMap = objectMap;
    }

    @Override
    public String getPath() {
        return "/api/delivery/instruction";
    }

    @Override
    public Map<String, String> getRequestParam() {
        return Collections.emptyMap();
    }

    @Override
    public String getRequestData() {
        String orderNo = objectMap.get("orderNo");
        log.debug("发票编号 {}", orderNo);
        List<String> fbInvoiceNoList = new ArrayList<>();
        fbInvoiceNoList.add(orderNo);
        Map<String, Object> data = new HashMap<>();
        // FB 发票编号（最多 200 个）
        data.put("fb_invoice_no", fbInvoiceNoList);
        // 送货指示请求人
        data.put("instruction_requester", "送货指示请求人");
        // 请求人联系方式
        data.put("requester_phone", "请求人联系方式");
        // 送货包装状态：O：按订单包装
        data.put("packing_status", "O");
        // 送货方式：P：快递，Q：快速送货，E：其他
        data.put("delivery_type", "P");
        // 快递公司名称
        data.put("parcel_company", "CJ 대한통운");
        // 发票编号
        data.put("invoice_no", "TEST20250930001");
        // 预计到货日期（YYYY-MM-DD）
        data.put("arrival_due_date", "2025-10-01");
        // 单行备忘录
        data.put("delivery_memo", "");
        // 备忘录
        data.put("memo", "");
        return JSON.toJSONString(data);
    }

    @Override
    public void processResponseResult(JSONObject jsonResult) {
        log.debug(">>>处理 配送说明 响应结果<<<");
        JSONObject meta = jsonResult.getJSONObject("meta");
        Integer code = meta.getInteger("code");
        String message = meta.getString("message");
        switch (code) {
            case 200:
                JSONObject response = jsonResult.getJSONObject("response");
                log.debug("响应成功 response: {}", response);
                // 发货指示编号
                String instructionNo = response.getString("instruction_no");
                log.debug("发货指示编号：{}", instructionNo);
                JSONArray result = response.getJSONArray("result");
                for (int i = 0; i < result.size(); i++) {
                    JSONObject item = result.getJSONObject(i);
                    ResultVO resultVO = new ResultVO();
                    resultVO.setInstructionNo(instructionNo);
                    resultVO.setFbInvoiceNo(item.getString("fb_invoice_no"));
                    resultVO.setOrdBundleNo(item.getString("ord_bundle_no"));
                    resultVO.setEcShopNo(item.getString("ec_shop_no"));
                    resultVO.setResult(item.getBoolean("result"));
                    resultVO.setResultReason(item.getString("result_reason"));
                    vos.add(resultVO);
                }
                break;
            case 440:
                log.error("必需参数错误：缺失或无效值。 message: {}", message);
                break;
            case 441:
                // 运输指示请求者为必填项; 包装状态为必填项
                log.error("code=441，message: {}", message);
                break;
            case 500:
                log.error("内部处理错误，message: {}", message);
                break;
            case 600:
                log.error("未知错误（未定义错误），message: {}", message);
                break;
            default:
                log.error("下单失败 code: {}", code);
                break;
        }
    }

    /**
     * 获取配送说明结果
     *
     * @return List<ResultVO>
     */
    public List<ResultVO> getResult() {
        log.debug("获取配送说明解析结果 {}", vos);
        return vos;
    }

    /**
     * 配送说明结果视图
     */
    public static class ResultVO {
        /**
         * 发货指示编号（主单号，与 resultvo 对象是父子关系）
         */
        private String instructionNo;
        /**
         * DeHub 发票号码
         */
        private String fbInvoiceNo;
        /**
         * 合浦号码
         */
        private String ordBundleNo;
        /**
         * EC多商城号
         */
        private String ecShopNo;
        /**
         * 配送指示结果（真/假）
         */
        private Boolean result;
        /**
         * 发货指示失败原因
         */
        private String resultReason;

        public String getInstructionNo() {
            return instructionNo;
        }

        public void setInstructionNo(String instructionNo) {
            this.instructionNo = instructionNo;
        }

        public String getFbInvoiceNo() {
            return fbInvoiceNo;
        }

        public void setFbInvoiceNo(String fbInvoiceNo) {
            this.fbInvoiceNo = fbInvoiceNo;
        }

        public String getOrdBundleNo() {
            return ordBundleNo;
        }

        public void setOrdBundleNo(String ordBundleNo) {
            this.ordBundleNo = ordBundleNo;
        }

        public String getEcShopNo() {
            return ecShopNo;
        }

        public void setEcShopNo(String ecShopNo) {
            this.ecShopNo = ecShopNo;
        }

        public Boolean getResult() {
            return result;
        }

        public void setResult(Boolean result) {
            this.result = result;
        }

        public String getResultReason() {
            return resultReason;
        }

        public void setResultReason(String resultReason) {
            this.resultReason = resultReason;
        }

        @Override
        public String toString() {
            return "ResultVO{" +
                    "instructionNo='" + instructionNo + '\'' +
                    ", fbInvoiceNo='" + fbInvoiceNo + '\'' +
                    ", ordBundleNo='" + ordBundleNo + '\'' +
                    ", ecShopNo='" + ecShopNo + '\'' +
                    ", result=" + result +
                    ", resultReason='" + resultReason + '\'' +
                    '}';
        }
    }
}
